<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${title}">配置编辑</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }

        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
            font-weight: 600;
        }

        .header p {
            font-size: 16px;
            opacity: 0.9;
        }

        .card {
            background: white;
            border-radius: 16px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #f8f9fa;
        }

        .page-title h3 {
            margin: 0;
            color: #333;
            font-size: 24px;
            font-weight: 600;
        }

        .page-title p {
            margin: 5px 0 0 0;
            color: #666;
            font-size: 14px;
        }

        .page-actions {
            display: flex;
            gap: 10px;
        }

        .btn-back {
            background: linear-gradient(135deg, #6c757d 0%, #5a6268 100%);
            color: white;
            padding: 12px 20px;
            border: none;
            border-radius: 25px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            box-shadow: 0 2px 8px rgba(108, 117, 125, 0.3);
        }

        .btn-back:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(108, 117, 125, 0.4);
            text-decoration: none;
            color: white;
        }

        .btn-back i {
            font-size: 12px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
        }

        .form-row {
            display: flex;
            gap: 15px;
        }

        .form-row .form-group {
            flex: 1;
        }

        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 25px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: transform 0.2s;
            margin-right: 10px;
        }

        .btn:hover {
            transform: translateY(-2px);
        }

        .btn-secondary {
            background: #6c757d;
        }

        .wechat-auth {
            background: #f8f9fa;
            border: 2px dashed #dee2e6;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            margin-bottom: 20px;
        }

        .wechat-auth .btn {
            margin-top: 10px;
        }

        .footer {
            text-align: center;
            color: white;
            opacity: 0.8;
            margin-top: 30px;
            font-size: 14px;
        }

        .error {
            background: #f8d7da;
            color: #721c24;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .success {
            background: #d4edda;
            color: #155724;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        /* 弹窗样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
            animation: fadeIn 0.3s;
        }

        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: none;
            border-radius: 12px;
            width: 80%;
            max-width: 400px;
            position: relative;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            animation: slideIn 0.3s;
        }

        .modal-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 15px;
        }

        .modal-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        .close {
            color: #aaa;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            line-height: 1;
        }

        .close:hover,
        .close:focus {
            color: #000;
            text-decoration: none;
        }

        .modal-body {
            padding: 10px 0;
            color: #666;
            line-height: 1.5;
        }

        .modal-footer {
            text-align: right;
            margin-top: 20px;
        }

        .modal-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 8px 20px;
            border: none;
            border-radius: 20px;
            font-size: 14px;
            cursor: pointer;
            transition: transform 0.2s;
        }

        .modal-btn:hover {
            transform: translateY(-2px);
        }

        .modal-btn-danger {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
        }

        .modal-btn-secondary {
            background: #6c757d;
            margin-right: 10px;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-50px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* 移动端优化样式 */
        @media (max-width: 768px) {
            .container {
                padding: 10px;
                max-width: 100%;
            }

            .header {
                margin-bottom: 20px;
            }

            .header h1 {
                font-size: 20px;
                margin-bottom: 5px;
            }

            .header p {
                font-size: 14px;
            }

            .card {
                padding: 15px;
                border-radius: 12px;
                margin-bottom: 15px;
            }

            .page-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
                padding-bottom: 15px;
            }

            .page-title h3 {
                font-size: 20px;
            }

            .page-title p {
                font-size: 13px;
            }

            .page-actions {
                width: 100%;
            }

            .btn-back {
                width: 100%;
                justify-content: center;
                padding: 14px 20px;
                font-size: 16px;
            }

            .form-row {
                flex-direction: column;
                gap: 0;
            }

            .form-group input,
            .form-group select,
            .form-group textarea {
                font-size: 16px; /* 防止iOS缩放 */
                padding: 12px;
            }

            .wechat-auth {
                padding: 15px;
                margin-bottom: 15px;
            }

            .wechat-auth h4 {
                font-size: 16px;
                margin-bottom: 8px;
            }

            .wechat-auth p {
                font-size: 13px;
                margin-bottom: 10px;
            }

            .modal-content {
                width: 90%;
                margin: 20% auto;
                padding: 20px 15px;
            }

            .modal-title {
                font-size: 16px;
            }

            .close {
                font-size: 24px;
            }
        }

        /* 超小屏幕优化 */
        @media (max-width: 480px) {
            .container {
                padding: 8px;
            }

            .card {
                padding: 12px;
            }

            .header h1 {
                font-size: 18px;
            }

            .wechat-auth {
                padding: 12px;
            }

            .modal-content {
                width: 95%;
                margin: 10% auto;
                padding: 15px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1 th:text="${title}">配置编辑</h1>
            <p th:text="${description}">配置股票异动提醒参数</p>
        </div>

        <div class="card">

            <!-- 微信授权区域 -->
            <div class="wechat-auth" id="wechat-auth-area" th:if="${openid == null or #strings.isEmpty(openid)}">
                <h4>🔐 微信消息推送授权</h4>
                <p>为了向您推送股票异动消息，需要获取您的微信OpenId</p>
                <button class="btn" onclick="getWechatAuth()">点击获取微信授权</button>
                <p style="margin-top: 10px; font-size: 14px; color: #666;">
                    当前OpenId: <span id="current-openid">未授权</span>
                </p>
            </div>

            <form id="config-form">
                <input type="hidden" id="config-id" th:value="${configId}">

                <div class="form-group">
                    <label for="stock-codes">股票代码 *</label>
                    <textarea id="stock-codes" rows="3" th:disabled="${configId} != null" placeholder="请输入股票代码，多个代码用英文逗号分隔，如：000001,000002,600000"></textarea>
                </div>

<!--                <div class="form-group">-->
<!--                    <label for="stock-names">股票名称</label>-->
<!--                    <textarea id="stock-names" rows="3" th:disabled="${configId} != null" placeholder="请输入对应的股票名称，多个名称用英文逗号分隔，如：平安银行,万科A,浦发银行"></textarea>-->
<!--                </div>-->

                <div class="form-row">
                    <div class="form-group">
                        <label for="rise-ratio">上涨预警比例 (%) *</label>
                        <input type="number" id="rise-ratio" step="0.01" min="0" max="100" placeholder="如：5.5">
                    </div>
                    <div class="form-group">
                        <label for="fall-ratio">下跌预警比例 (%) *</label>
                        <input type="number" id="fall-ratio" step="0.01" min="0" max="100" placeholder="如：5.5">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="push-type">消息推送类型</label>
                        <select id="push-type">
                            <option value="1">微信服务号推送</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="push-frequency">推送频率 (分钟) *</label>
                        <input type="number" id="push-frequency" min="1" max="1440" value="30" placeholder="如：30">
                    </div>
                </div>

                <div class="form-group">
                    <label for="alert-enabled">是否启用预警</label>
                    <select id="alert-enabled">
                        <option value="1">启用</option>
                        <option value="0">关闭</option>
                    </select>
                </div>

                <!-- 消息提示区域 -->
                <div id="message-area"></div>

                <!-- 错误信息显示 -->
                <div th:if="${errorMessage != null}" class="error" th:text="${errorMessage}"></div>

                <div style="text-align: center; margin-top: 30px;">
                    <button type="button" class="btn" onclick="saveConfig()">保存配置</button>
                    <button type="button" class="btn btn-secondary" onclick="resetForm()">重置</button>
                </div>
            </form>
        </div>

        <div class="footer">
            <p>© 2025 Witmore AI - 让投资更智能</p>
        </div>
    </div>

    <script src="https://witmore.oss-cn-hangzhou.aliyuncs.com/cdn/npm/font-awesome/6.4.0/all.min.js"></script>
    <script>
        // 全局变量
        let currentOpenId = '';

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkWechatAuth();

            // 如果是编辑模式，加载配置数据
            const configId = document.getElementById('config-id').value;
            if (configId) {
                loadConfigData(configId);
            }

            // 添加股票代码输入监听
            const stockCodesInput = document.getElementById('stock-codes');
            if (stockCodesInput) {
                stockCodesInput.addEventListener('blur', function() {
                    autoFillStockNames();
                });
            }
        });

        // 显示消息
        function showMessage(message, type = 'success') {
            const messageArea = document.getElementById('message-area');
            messageArea.innerHTML = `<div class="${type}">${message}</div>`;
            setTimeout(() => {
                messageArea.innerHTML = '';
            }, 3000);
        }

        // 检查微信授权状态
        function checkWechatAuth() {
            // 从localStorage获取已保存的OpenId
            const openId = localStorage.getItem('wechat_openid');
            if (openId) {
                currentOpenId = openId;
                document.getElementById('current-openid').textContent = openId;
            }
        }

        // 获取微信授权
        function getWechatAuth() {
            // 直接跳转到微信授权页面
            window.location.href = '/wechat/qrcode';
        }

        // 加载配置数据（编辑模式）
        function loadConfigData(configId) {
            fetch(`/api/wechat/stock-alert/get/${configId}`)
            .then(response => {
                if (response.status === 401) {
                    const redirectUrl = '/login/sms?redirect=' + encodeURIComponent(window.location.pathname + window.location.search);
                    window.location.href = redirectUrl;
                    return;
                }
                return response.json();
            })
            .then(result => {
                if (!result) return;

                if (result.code === 200 || result.code === 0) {
                    const config = result.data;

                    // 填充表单
                    document.getElementById('stock-codes').value = config.stockCodes || '';
                    // document.getElementById('stock-names').value = config.stockNames || '';
                    document.getElementById('rise-ratio').value = config.riseRatio || '';
                    document.getElementById('fall-ratio').value = config.fallRatio || '';
                    document.getElementById('push-type').value = config.pushType || 1;
                    document.getElementById('push-frequency').value = config.pushFrequency || 30;
                    document.getElementById('alert-enabled').value = config.alertEnabled || 1;

                    if (config.wechatOpenId) {
                        currentOpenId = config.wechatOpenId;
                        document.getElementById('current-openid').textContent = config.wechatOpenId;
                    }
                } else {
                    if (result.code === 401) {
                        const redirectUrl = '/login/sms?redirect=' + encodeURIComponent(window.location.pathname + window.location.search);
                        window.location.href = redirectUrl;
                        return;
                    }
                    showMessage(result.message || '获取配置失败', 'error');
                }
            })
            .catch(error => {
                console.error('获取配置失败:', error);
                showMessage('网络错误，请稍后重试', 'error');
            });
        }

        // 自动填充股票名称
        function autoFillStockNames() {
            const stockCodesInput = document.getElementById('stock-codes');
            // const stockNamesInput = document.getElementById('stock-names');

            if (!stockCodesInput || !stockNamesInput) return;

            const stockCodes = stockCodesInput.value.trim();
            if (!stockCodes) {
                stockNamesInput.value = '';
                return;
            }

            // 如果用户已经手动填写了股票名称，就不覆盖
            if (stockNamesInput.value.trim()) {
                return;
            }

            // 分解股票代码
            const codes = stockCodes.split(',').map(code => code.trim()).filter(code => code);

            // 简单的股票代码-名称映射表（常见股票）
            const stockCodeMap = {
                '000001': '平安银行',
                '000002': '万科A',
                '000858': '五粮液',
                '002415': '海康威视',
                '300059': '东方财富',
                '600000': '浦发银行',
                '600036': '招商银行',
                '600519': '贵州茅台',
                '600887': '伊利股份'
            };

            // 尝试自动填充名称
            const names = codes.map(code => {
                return stockCodeMap[code] || ''; // 如果找不到对应的名称，则留空
            });

            // 只有当所有股票代码都能找到对应名称时才自动填充
            if (names.every(name => name !== '')) {
                stockNamesInput.value = names.join(',');
                showMessage('已自动填充股票名称', 'success');
            } else {
                showMessage('请手动填写股票名称', 'info');
            }
        }

        // 保存配置
        function saveConfig() {
            const configId = document.getElementById('config-id').value;
            const stockCodes = document.getElementById('stock-codes').value.trim();
            // const stockNames = document.getElementById('stock-names').value.trim();
            const riseRatio = document.getElementById('rise-ratio').value;
            const fallRatio = document.getElementById('fall-ratio').value;
            const pushType = document.getElementById('push-type').value;
            const pushFrequency = document.getElementById('push-frequency').value;
            const alertEnabled = document.getElementById('alert-enabled').value;

            // 表单验证
            if (!stockCodes) {
                showMessage('请输入股票代码', 'error');
                return;
            }
            if (!riseRatio || !fallRatio || !pushFrequency) {
                showMessage('请填写完整的预警配置信息', 'error');
                return;
            }

            const configData = {
                id: configId || null,
                stockCodes: stockCodes,
                // stockNames: stockNames,
                riseRatio: parseFloat(riseRatio),
                fallRatio: parseFloat(fallRatio),
                pushType: parseInt(pushType),
                pushFrequency: parseInt(pushFrequency),
                alertEnabled: parseInt(alertEnabled),
                wechatOpenId: currentOpenId
            };

            const url = configId ? '/api/wechat/stock-alert/update' : '/api/wechat/stock-alert/create';
            const method = configId ? 'PUT' : 'POST';

            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(configData)
            })
            .then(response => {
                if (response.status === 401) {
                    const redirectUrl = '/login/sms?redirect=' + encodeURIComponent(window.location.pathname + window.location.search);
                    window.location.href = redirectUrl;
                    return;
                }
                return response.json();
            })
            .then(result => {
                if (!result) return;

                // 判断成功：code为成功码（通常是200或0）
                if (result.code === 200 || result.code === 0) {
                    showMessage(configId ? '更新成功' : '创建成功', 'success');
                    setTimeout(() => {
                        // 重新加载页面以显示最新数据
                        window.location.href = '/wechat/h5/config-tool/r6FisgH5ve7ylkCA';
                    }, 1000);
                } else {
                    if (result.code === 401) {
                        const redirectUrl = '/login/sms?redirect=' + encodeURIComponent(window.location.pathname + window.location.search);
                        window.location.href = redirectUrl;
                        return;
                    }
                    showMessage(result.message || '保存失败', 'error');
                }
            })
            .catch(error => {
                console.error('保存配置失败:', error);
                showMessage('网络错误，请稍后重试', 'error');
            });
        }

        // 重置表单
        function resetForm() {
            const configId = document.getElementById('config-id').value;
            document.getElementById('config-form').reset();
            document.getElementById('config-id').value = configId; // 保持configId不变
            document.getElementById('push-frequency').value = '30';
        }

        // 处理微信授权回调（如果在同一页面）
        function handleWechatAuthCallback() {
            const urlParams = new URLSearchParams(window.location.search);
            const code = urlParams.get('code');

            if (code) {
                fetch(`/api/wechat/stock-alert/wechat-auth-callback?code=${code}`)
                .then(response => {
                    if (response.status === 401) {
                        const redirectUrl = '/login/sms?redirect=' + encodeURIComponent(window.location.pathname + window.location.search);
                        window.location.href = redirectUrl;
                        return;
                    }
                    return response.json();
                })
                .then(result => {
                    if (!result) return;

                    if (result.code === 200 || result.code === 0) {
                        currentOpenId = result.data;
                        localStorage.setItem('wechat_openid', currentOpenId);
                        document.getElementById('current-openid').textContent = currentOpenId;
                        showMessage('微信授权成功', 'success');
                    } else {
                        if (result.code === 401) {
                            const redirectUrl = '/login/sms?redirect=' + encodeURIComponent(window.location.pathname + window.location.search);
                            window.location.href = redirectUrl;
                            return;
                        }
                        showMessage(result.message || '授权失败', 'error');
                    }
                })
                .catch(error => {
                    console.error('处理微信授权回调失败:', error);
                    showMessage('授权处理失败', 'error');
                });
            }
        }

        // 检查URL中是否有授权回调参数
        if (window.location.search.includes('code=')) {
            handleWechatAuthCallback();
        }
    </script>
</body>
</html>
